/**
 * 
 */
package lifemain;

import java.util.concurrent.*;
/**
 * @author kin
 *
 */

public class nextStep {

	final CyclicBarrier barrier;
	
	public class Step implements Runnable {
	
		/**
		 * 
		 */
		matrix m_res;
		int i;
		int j;
		matrix old;
		public Thread t;
		public Step(int n, int m, int _i, int _j,matrix _old) {
		
			m_res= new matrix(n,m);
			i=_i;
			j=_j;
			old = _old;
			t= new Thread (this);
			t.start();
		}
	
		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() 
		{
			
			
			for (int k=0; k<m_res.getN(); k++)
			{
				for (int t=0; t<m_res.getM(); t++)
				{
					matrix el=old.getNPole(i+k,j+t);
					int s=0;
					for (int k1=0; k1<3; k1++)
						for (int t1=0; t1<3; t1++)
							if (el.getPole(k1, t1)) 
							{
								s=s+1;
							}
					if (el.getPole(1, 1))
					{
						s=s-1;
					}
					if (old.getPole(i+k,j+t))
					{
						if ((s<2) || (s>3))	
						{
							m_res.nosetPole(k, t);
						}
						else m_res.setPole(k, t);
					}
					else
					{
						if (s==3) m_res.setPole(k, t);
					}
				}
			}
		
			try 
			{
		        barrier.await(); 
		    } 
			catch (InterruptedException ex) 
			{ 
		        return; 
		    } 
			catch (BrokenBarrierException ex) 
			{ 
		        return; 
		    }
			
			
			for (int k=0; k<m_res.getN(); k++)
			{
				for (int t=0; t<m_res.getM(); t++)
				{
					if (m_res.getPole(k,t))
					{
						old.setPole(i+k, j+t);
					}
					else
					{
						old.nosetPole(i+k, j+t);
					}
				}
			}
			
				
		}
	
	}
	
	public nextStep(matrix old)
	{
		barrier = new CyclicBarrier(4);
		
		int k,t,i,j;
		int n,m;
		n = old.getN();
		m = old.getM();
		k=n/2;
		t=n-k;
		i=m/2;
		j=m-i;
		
			
		Step st1 = new Step(k,i,0,0,old);
		Step st2 = new Step(t,i,k,0,old);
		Step st3 = new Step(k,j,0,i,old);
		Step st4 = new Step(t,j,k,i,old);
		
		try
		{
			st1.t.join();
			st2.t.join();
			st3.t.join();
			st4.t.join();
		} 
		catch (InterruptedException ex) 
		{ 
			System.out.print("Ошибка");
		}
	
	}


}
